package com.zh.zcy.filter;

import com.zh.zcy.entity.User;
import com.zh.zcy.untils.UserContextUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@Component
public class MyFilter implements Filter {

    // 动态注入白名单路径（非 static）
    @Value("${security.white-list}")
    private List<String> whiteList;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("MyFilter的init方法。。。。。。");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;

        System.out.println("MyFilter的doFilter方法。。。。。。");
        // 检查是否是白名单路径
        String requestURI = req.getRequestURI();
        if (isWhiteList(requestURI)) {
            // 直接放行，不执行过滤逻辑
            filterChain.doFilter(request, response);
            return;
        }
        filterChain.doFilter(request,response);
        /*int userId = Integer.parseInt(req.getHeader("userId"));
        String userName = req.getHeader("userName");
        int userAge = Integer.parseInt(req.getHeader("userAge"));
        User user = new User(userId,userName,userAge);
        UserContextUtil.setUser(user);*/

    }

    @Override
    public void destroy() {
        System.out.println("MyFilter的destroy方法。。。。。。");
        System.out.println("User被clear前:"+UserContextUtil.getUser());
        UserContextUtil.clear();
        System.out.println("User被clear后:"+UserContextUtil.getUser());
    }

    private boolean isWhiteList(String uri) {
        AntPathMatcher pathMatcher = new AntPathMatcher();
        return whiteList.stream().anyMatch(pattern -> pathMatcher.match(pattern, uri));
    }
}
